package com.shop.web.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.shop.domain.Order;
import com.shop.domain.OrderItem;
import com.shop.domain.Product;
import com.shop.domain.User;
import com.shop.service.OrderService;

/**
 * 商品上传
 * 
 * @author Administrator
 * 
 */
public class AddOrdersServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3711980669364366170L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Order order = new Order();
		List<OrderItem> items = new ArrayList<OrderItem>();
		//第一步：添加收货人信息
		String receiverinfo = request.getParameter("receiverinfo");
		order.setReceiverinfo(receiverinfo);
		
		//第二步：添加购买人id
		User user = (User) request.getSession().getAttribute("loginUser");
		order.setUser_id(user.getId());
		
		//第三步：得到购物车信息
		@SuppressWarnings("unchecked")
		Map<Product, Integer> carts = (Map<Product, Integer>) request.getSession().getAttribute("cart"); 
		//第四步：得到订单总金额
		int totalMoney = 0;
		for(Map.Entry<Product, Integer> entry : carts.entrySet()){
			totalMoney += entry.getKey().getPrice() * entry.getValue();
			//第五步：生成订单项
			OrderItem item = new OrderItem();
			item.setBuynum(entry.getValue());
			item.setMoney(entry.getKey().getPrice() * entry.getValue());
			item.setProduct_id(entry.getKey().getId());
			items.add(item);
		}
		order.setTotalmoney(totalMoney);
		order.setOrderItems(items);
		
		OrderService service = new OrderService();
		service.addOrders(order);
		
		//清空购物车
		request.getSession().removeAttribute("cart");
		response.getWriter().println("订单已经生成,<a href='listOrders'>查看订单</a>");
		
		
		
	}

}
